import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:rabbit_mobile/view/Home/models/home_model.dart';
import 'package:rabbit_mobile/source/language_constant.dart';
import 'package:rabbit_mobile/widget/custom_cache_image_widget/index.dart';
import 'package:shimmer/shimmer.dart';

class HomeCategoryWidget extends StatefulWidget {
  final AsyncValue categoryData;
  const HomeCategoryWidget({
    super.key,
    required this.categoryData,
  });

  @override
  State<HomeCategoryWidget> createState() => _HomeCategoryWidgetState();
}

class _HomeCategoryWidgetState extends State<HomeCategoryWidget> {
  bool height_bool = true;
  int page_num = 0;
  int pageviewCurrentIndex = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {});
    });
  }

  List<Widget> _buildCategoryWidget(
      List<CategoryGrids> categoryData, double _imageHeight) {
    List<Widget> itemCategoryList = [];
    for (var itemCategory in categoryData) {
      itemCategoryList.add(
        InkWell(
          focusColor: Colors.transparent,
          hoverColor: Colors.transparent,
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          onTap: () {
            context.beamToNamed('/child_home/${itemCategory.id}');
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CustomCacheImageWidget(
                imageUrl: itemCategory.picture ?? "",
                width: 60,
                height: 60,
              ),
              SizedBox(
                height: 20,
                width: 60,
                child: Text(
                  homePageLanguage(itemCategory.name ?? ""),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  textAlign: TextAlign.center,
                ),
              )
            ],
          ),
        ),
      );
    }
    return itemCategoryList;
  }

  List<Widget> _pageViewPagination(int index) {
    List<Widget> pageViewPagination = [];
    for (var i = 0; i < page_num; i++) {
      pageViewPagination.add(
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 4.0),
          width: 20,
          height: 3,
          decoration: BoxDecoration(
              color: index == i ? Colors.teal : Colors.grey.shade300,
              borderRadius: BorderRadius.circular(10)),
        ),
      );
    }
    return pageViewPagination;
  }

  List<Widget> _buildStaggeredGridView(
      int pages, List<CategoryGrids> categoryData, double _imageHeight) {
    List<Widget> itemStaggeredBuild = [];
    for (var i = 0; i < pages; i++) {
      if (i == pages - 1) {
        itemStaggeredBuild.add(
          Align(
            alignment: Alignment.center,
            child: AlignedGridView.count(
              crossAxisCount: categoryData.length % 10 >= 5 ? 5 : 4,
              crossAxisSpacing: 2,
              mainAxisSpacing: 10,
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: categoryData.length % 10,
              itemBuilder: (context, index) {
                final currentIndex = (pages * 10 + index) - 10;
                final item = categoryData[currentIndex];
                return InkWell(
                  focusColor: Colors.transparent,
                  hoverColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  splashColor: Colors.transparent,
                  onTap: () {
                    context.beamToNamed('/child_home/${item.id}');
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      CustomCacheImageWidget(
                        imageUrl: item.picture ?? "",
                        width: 60,
                        height: 60,
                      ),
                      SizedBox(
                        height: 20,
                        width: 60,
                        child: Text(
                          homePageLanguage(item.name ?? ""),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                        ),
                      )
                    ],
                  ),
                );
              },
            ),
          ),
        );
        return itemStaggeredBuild;
      }
      itemStaggeredBuild.add(
        Align(
          alignment: Alignment.center,
          child: StaggeredGrid.count(
            crossAxisCount: 2,
            crossAxisSpacing: 2,
            mainAxisSpacing: 20,
            children: _buildCategoryWidget(
                [...categoryData.sublist(0, 10)], _imageHeight),
          ),
        ),
      );
    }
    return itemStaggeredBuild;
  }

  @override
  Widget build(BuildContext context) {
    // 獲取屏幕的高度
    double screenWidth = MediaQuery.of(context).size.width;
    // 計算圖片的高度
    final imageHeight = (screenWidth - 6 * 10) * 0.2;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          AnimatedContainer(
            duration: const Duration(microseconds: 400),
            curve: Curves.easeInOut,
            height: height_bool ? 210 : 120,
            child: Container(
              margin: const EdgeInsets.only(top: 20.0),
              width: double.infinity,
              height: 180.0,
              child: widget.categoryData.when(
                data: (data) {
                  int pages = ([
                            ...data.categoryGrids,
                            ...data.categoryGrids.sublist(0, 6)
                          ].length *
                          0.1)
                      .ceil();
                  setState(() => page_num = pages);
                  return PageView(
                    children: _buildStaggeredGridView(
                      pages,
                      [
                        ...data.categoryGrids,
                        ...data.categoryGrids.sublist(0, 6)
                      ],
                      imageHeight,
                    ),
                    onPageChanged: (int index) {
                      List dataList = [
                        ...data.categoryGrids,
                        ...data.categoryGrids.sublist(0, 6)
                      ];
                      int remainingItems = dataList.length - index * 10;
                      setState(() {
                        height_bool = remainingItems > 5;
                        pageviewCurrentIndex = index;
                      });
                    },
                  );
                },
                error: (error, StackTrace) => const Center(
                  child: Center(
                    child: Column(
                      children: [
                        Icon(
                          Icons.dangerous,
                          color: Colors.red,
                          size: 30,
                        ),
                        Text(
                          "數據錯誤，請稍後再試",
                          style: TextStyle(fontSize: 16.0),
                        )
                      ],
                    ),
                  ),
                ),
                loading: () => AlignedGridView.count(
                  crossAxisCount: 5,
                  crossAxisSpacing: 2,
                  mainAxisSpacing: 22,
                  itemCount: 10,
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) {
                    return Shimmer.fromColors(
                      baseColor: Colors.grey.shade300,
                      highlightColor: Colors.grey.shade400,
                      child: Column(
                        children: [
                          Container(
                            width: 60.0,
                            height: 60.0,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10.0),
                              color: Colors.teal,
                            ),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          Container(
                            width: 60.0,
                            height: 10,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10.0),
                                color: Colors.teal),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
          ),
          SizedBox(
            width: double.infinity,
            height: 10,
            child: Align(
              alignment: Alignment.topCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: _pageViewPagination(pageviewCurrentIndex),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
